﻿using IOA.MES.Business;
using IOA.MES.DataAccess.Entity;
using IOA.MES.DataAccess.Enum;
using IOA.MES.DataAccess.VModel;
using IOA.MES.Web.App_Start;
using IOA.MES.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.ModelBinding;
using System.Web.Mvc;
using System.Web.UI.WebControls;

namespace IOA.MES.Web.Controllers
{
    /// <summary>
    /// 系统设置
    /// </summary>
    public class SettingsController : Controller
    {
        #region 部门管理
        /// <summary>
        /// 部门管理
        /// </summary>
        public ActionResult DepartmentMgr()
        {
            return View();
        }

        /// <summary>
        /// 编辑部门
        /// </summary>
        [HttpPost]
        public JsonResult EditDepartment(VDepartment model)
        {
            model.CreateBy = BaseEnv.UserId;
            if (model.PkId > 0)
            {
                model.ModifyBy = BaseEnv.UserId;
            }
            model = new DepartmentMgr().EditDepartment(model);

            return Json(new ResultJson<object>(model));
        }

        /// <summary>
        /// 删除部门
        /// </summary>
        [HttpPost]
        public JsonResult DeleteDepartment(int departmentId)
        {
            new DepartmentMgr().DeleteDepartment(new VDepartment { PkId = departmentId, ModifyBy = BaseEnv.UserId });

            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 查询部门树
        /// </summary>
        [HttpPost]
        public JsonResult QueryDepartmentsTree()
        {
            var departments = new DepartmentMgr().QueryUserDepartments(BaseEnv.UserId);

            var tree = new List<TreeModel>();
            var parents = departments.Where(_ => !departments.Select(d => d.PkId).Contains(_.ParentId)).ToList();
            foreach (var parent in parents)
            {
                var node = new TreeModel
                {
                    id = parent.PkId,
                    title = parent.DepartmentName,
                    field = "DepartmentId"
                };
                node.children.AddRange(GetTreeModels(departments, parent.PkId));
                tree.Add(node);
            }
            return Json(new ResultJson<List<TreeModel>>(tree));
        }
        private List<TreeModel> GetTreeModels(List<VDepartment> models, int parentId)
        {
            var trees = models.Where(_ => _.ParentId == parentId).Select(_ => new TreeModel
            {
                id = _.PkId,
                title = _.DepartmentName,
                field = "DepartmentId"
            }).ToList();
            foreach (var item in trees)
            {
                item.children.AddRange(GetTreeModels(models, item.id));
            }

            return trees;
        }
        #endregion

        #region 岗位管理
        /// <summary>
        /// 岗位管理
        /// </summary>
        public ActionResult RoleMgr()
        {
            ViewBag.Departments = new DepartmentMgr().QueryUserDepartments(BaseEnv.UserId);
            return View();
        }

        /// <summary>
        /// 编辑岗位页面
        /// </summary>
        public ActionResult EditRole(int roleId)
        {
            ViewBag.Departments = new DepartmentMgr().QueryUserDepartments(BaseEnv.UserId);
            var role = roleId <= 0 ? null : new RoleMgr().GetRole(roleId);
            return View(role);
        }

        /// <summary>
        /// 编辑岗位接口
        /// </summary>
        [HttpPost]
        public JsonResult EditRole(VRole model)
        {
            if (model.PkId <= 0)
            {
                model.CreateBy = BaseEnv.UserId;
            }
            else
            {
                model.ModifyBy = BaseEnv.UserId;
            }
            new RoleMgr().EditRole(model);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 编辑岗位接口
        /// </summary>
        [HttpPost]
        public JsonResult DeleteRole(VRole model)
        {
            model.ModifyBy = BaseEnv.UserId;
            new RoleMgr().DeleteRole(model);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 查询所有岗位
        /// </summary>
        [HttpPost]
        public JsonResult QueryRoles(int page, int limit, int departmentId, string roleName)
        {
            var departments = departmentId <= 0 ? new DepartmentMgr().QueryUserDepartments(BaseEnv.UserId) : new DepartmentMgr().QuerySubDepartments(departmentId, true);
            var total = 0;
            var roles = new RoleMgr().QueryRoles(page, limit, out total, departments.Select(_ => _.PkId).ToList(), roleName);
            return Json(new ResultJson<object>(roles, total));
        }

        /// <summary>
        /// 岗位权限管理
        /// </summary>
        public ActionResult RolePowerMgr(int roleId)
        {
            var role = new RoleMgr().GetRole(roleId);
            return View(role);
        }

        /// <summary>
        /// 查询权限列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryPowers(int roleId)
        {
            var powers = new ModuleMgr().QueryModules(BaseEnv.UserId);
            var roleModuleIds = new ModuleMgr().QueryRoleModules(roleId).Select(_ => _.ModuleId).Distinct().ToList();
            var trees = GetTree(0, powers, roleModuleIds);
            return Json(new ResultJson<object>(trees, trees.Count));
        }
        private List<TreeModel> GetTree(int parentId, List<VModule> modules, List<int> roleModuleIds)
        {
            var curModules = modules.Where(_ => _.ParentId == parentId && _.Valid).Select(_ => new TreeModel
            {
                id = _.PkId,
                url = _.Url,
                title = _.CNTitle,
                spread = true,
                @checked = roleModuleIds.Contains(_.PkId),
                children = new List<TreeModel>()
            }).ToList();
            for (int i = curModules.Count - 1; i >= 0; i--)
            {
                curModules[i].children = GetTree(curModules[i].id, modules, roleModuleIds);
                if (string.IsNullOrWhiteSpace(curModules[i].url) && !curModules[i].children.Any())
                {
                    curModules.RemoveAt(i);
                }
            }

            return curModules;
        }

        /// <summary>
        /// 查询权限列表
        /// </summary>
        [HttpPost]
        public JsonResult SaveRolePowers(int roleId, List<int> moduleIds)
        {
            new ModuleMgr().SaveRoleModules(roleId, moduleIds, BaseEnv.UserId);
            return Json(new ResultJson<object>());
        }
        #endregion

        #region 车间管理
        /// <summary>
        /// 车间管理
        /// </summary>
        public ActionResult WorkshopMgr()
        {
            return View();
        }

        /// <summary>
        /// 编辑车间页面
        /// </summary>
        public ActionResult EditWorkshop(int workshopId)
        {
            var workshop = workshopId <= 0 ? null : new WorkshopMgr().GetWorkshop(workshopId);
            return View(workshop);
        }

        /// <summary>
        /// 编辑车间接口
        /// </summary>
        [HttpPost]
        public JsonResult EditWorkshop(VWorkshop model)
        {
            if (model.PkId <= 0)
            {
                model.CreateBy = BaseEnv.UserId;
            }
            else
            {
                model.ModifyBy = BaseEnv.UserId;
            }
            new WorkshopMgr().EditWorkshop(model);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 查询所有车间
        /// </summary>
        [HttpPost]
        public JsonResult QueryWorkshops(int page, int limit, WorkshopStatus? status, string workshopName)
        {
            var total = 0;
            var workshops = new WorkshopMgr().QueryWorkshops(page, limit, out total, status, workshopName);
            return Json(new ResultJson<object>(workshops, total));
        }
        #endregion

        #region 用户管理
        /// <summary>
        /// 编辑用户页面
        /// </summary>
        public ActionResult EditUser(int userId)
        {
            ViewBag.Roles = new RoleMgr().QueryUserManageRoles(BaseEnv.UserId);
            ViewBag.Workshops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            ViewBag.Sites = new MachineMgr().QueryMachineTypes();
            var user = userId <= 0 ? new VUser() : new UserMgr().GetUser(userId);

            return View(user);
        }

        /// <summary>
        /// 编辑用户接口
        /// </summary>
        [HttpPost]
        public JsonResult EditUser(VUser model, List<MachineType> machineTypes)
        {
            model.Sites = machineTypes == null ? new List<KeyValuePair<MachineType, string>>() : machineTypes.Select(_ => new KeyValuePair<MachineType, string>(_, "")).ToList();
            if (model.PkId > 0)
            {
                model.ModifyBy = BaseEnv.UserId;
            }
            else
            {
                model.Password = BaseEnv.EncripyPassword("123456");
                model.CreateBy = BaseEnv.UserId;
                model.Status = CommonStatus.Normal;
            }
            new UserMgr().EditUser(model);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 禁用用户
        /// </summary>
        [HttpPost]
        public JsonResult ModifyUserStatus(int userId, CommonStatus status)
        {
            new UserMgr().ModifyStatus(new VUser { PkId = userId, Status = status, ModifyBy = BaseEnv.UserId });
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        [HttpPost]
        public JsonResult DeleteUser(int userId)
        {
            new UserMgr().DeleteUser(new VUser { PkId = userId, ModifyBy = BaseEnv.UserId });
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 用户管理
        /// </summary>
        public ActionResult UserMgr()
        {
            ViewBag.Departments = new DepartmentMgr().QueryUserDepartments(BaseEnv.UserId);
            ViewBag.Workshops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            return View();
        }

        /// <summary>
        /// 查询用户列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryUsers(int page, int limit, int departmentId, int roleId, string workshopCode, CommonStatus? status, string key)
        {
            var userDepartmentIds = (departmentId > 0 ? new DepartmentMgr().QuerySubDepartments(departmentId, true) : new DepartmentMgr().QueryUserDepartments(BaseEnv.UserId)).Select(_ => _.PkId).Distinct().ToList();
            var workshopCodes = string.IsNullOrWhiteSpace(workshopCode) ? new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId).Select(_ => _.WorkshopCode).ToList() : new List<string> { workshopCode };
            var total = 0;
            var models = new UserMgr().QueryUsers(page, limit, out total, userDepartmentIds, roleId, workshopCodes, status, key);
            return Json(new ResultJson<object>(models, total));
        }

        /// <summary>
        /// 修改密码页面
        /// </summary>
        public ActionResult ModifyPassword()
        {
            return View();
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        [HttpPost]
        public JsonResult ModifyPassword(string oldPwd, string newPwd)
        {
            new UserMgr().ModifyPassword(BaseEnv.UserId, oldPwd, newPwd);
            new FormsAuthenticationService().SignOut();
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        [HttpPost]
        public JsonResult ResetPassword(int userId)
        {
            new UserMgr().ResetPassword(userId);
            return Json(new ResultJson<object>());
        }
        #endregion

        #region 班次管理
        /// <summary>
        /// 班次管理
        /// </summary>
        public ActionResult DutyMgr(int workshopId = 0)
        {
            var workShops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            ViewBag.WorkshopId = workshopId;
            return View(workShops);
        }

        /// <summary>
        /// 班次编辑页
        /// </summary>
        public ActionResult EditDuty(int dutyId = 0)
        {
            var workShops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            ViewBag.WorkShops = workShops;

            var duty = dutyId <= 0 ? null : new WorkshopDutyMgr().GetDuty(dutyId);
            return View(duty);
        }

        /// <summary>
        /// 班次编辑接口
        /// </summary>
        [HttpPost]
        public JsonResult EditDuty(VWorkshopDuty model)
        {
            if (model.PkId <= 0)
            {
                model.CreateBy = BaseEnv.UserId;
            }
            else
            {
                model.ModifyBy = BaseEnv.UserId;
            }
            new WorkshopDutyMgr().EditDuty(model);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 修改班次状态
        /// </summary>
        [HttpPost]
        public JsonResult ModifyDutyStatus(int dutyId, CommonStatus status)
        {
            new WorkshopDutyMgr().ModifyStatus(new VWorkshopDuty { PkId = dutyId, Status = status, ModifyBy = BaseEnv.UserId });
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 查询班次列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryDuties(int page, int limit, string workshopCode, CommonStatus? status)
        {
            var total = 0;
            var duties = new WorkshopDutyMgr().QueryDuties(page, limit, out total, workshopCode, status);
            return Json(new ResultJson<object>(duties, total));
        }
        #endregion

        #region 流水线管理
        /// <summary>
        /// 流水线管理
        /// </summary>
        public ActionResult AssemblyLineMgr(string workshopCode = "")
        {
            var workShops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            ViewBag.WorkshopCode = workshopCode;
            return View(workShops);
        }

        /// <summary>
        /// 流水线编辑页
        /// </summary>
        public ActionResult EditLine(int lineId = 0)
        {
            var workShops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            ViewBag.WorkShops = workShops;

            var line = lineId <= 0 ? null : new AssemblyLineMgr().GetLine(lineId);
            return View(line);
        }

        /// <summary>
        /// 流水线编辑接口
        /// </summary>
        [HttpPost]
        public JsonResult EditLine(VAssemblyLine model)
        {
            if (model.PkId <= 0)
            {
                model.CreateBy = BaseEnv.UserId;
            }
            else
            {
                model.ModifyBy = BaseEnv.UserId;
            }
            new AssemblyLineMgr().EditLine(model);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 修改流水线状态
        /// </summary>
        [HttpPost]
        public JsonResult ModifyLineStatus(int lineId, CommonStatus status)
        {
            new AssemblyLineMgr().ModifyStatus(new VAssemblyLine { PkId = lineId, Status = status, ModifyBy = BaseEnv.UserId });
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 查询流水线列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryLines(int page, int limit, string workshopCode, CommonStatus? status)
        {
            var total = 0;
            var duties = new AssemblyLineMgr().QueryLines(page, limit, out total, workshopCode, status);
            return Json(new ResultJson<object>(duties, total));
        }
        #endregion

        #region 设备管理
        /// <summary>
        /// 设备管理
        /// </summary>
        public ActionResult MachineMgr(string workshopCode = "", int lineId = 0)
        {
            var workShops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            ViewBag.WorkshopCode = workshopCode;
            ViewBag.LineId = lineId;
            return View(workShops);
        }

        /// <summary>
        /// 设备编辑页
        /// </summary>
        public ActionResult EditMachine(int machineId = 0)
        {
            var machineTypes = new MachineMgr().QueryMachineTypes();
            var workShops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            ViewBag.MachineTypes = machineTypes;
            ViewBag.WorkShops = workShops;

            var machine = machineId <= 0 ? null : new MachineMgr().GetMachine(machineId);
            return View(machine);
        }

        /// <summary>
        /// 设备编辑接口
        /// </summary>
        [HttpPost]
        public JsonResult EditMachine(VMachine model)
        {
            if (model.PkId <= 0)
            {
                model.CreateBy = BaseEnv.UserId;
            }
            else
            {
                model.ModifyBy = BaseEnv.UserId;
            }
            new MachineMgr().EditMachine(model);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 修改设备状态
        /// </summary>
        [HttpPost]
        public JsonResult ModifyMachineStatus(int machineId, CommonStatus status)
        {
            new MachineMgr().ModifyStatus(new VMachine { PkId = machineId, Status = status, ModifyBy = BaseEnv.UserId });
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 查询设备列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryMachines(int page, int limit, string workshopCode, int lineId, CommonStatus? status, MachineType? machineType = null)
        {
            var total = 0;
            var machines = new MachineMgr().QueryMachines(page, limit, out total, workshopCode, lineId, status, machineType);
            return Json(new ResultJson<object>(machines, total));
        }
        #endregion
    }
}
